package com.liuwei.spring.cloud.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author : ImageHelper
 * @version V1.0
 * @date: 2023/12/29 2:04 PM
 * @Description: TODO
 */
public class ImageHelper {

    public static BufferedImage readImage(File file) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(file);
        return bufferedImage;
    }

    public static void saveImage(File targetFile,BufferedImage source,String imageFormat) throws IOException {
        ImageIO.write(source,imageFormat,targetFile);
    }

    public static BufferedImage getTrimImage(BufferedImage bufferedImage,int margin){
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        int[] arr = bufferedImageToIntArray(bufferedImage, width, height);
        BufferedImage newBufferedImage = bufferedImage.getSubimage(arr[0] - margin, arr[1] - margin, arr[2] + margin * 2, arr[3] + margin * 2);
        return newBufferedImage;
    }

    public static int[] bufferedImageToIntArray(BufferedImage image, int width, int height) {
        int WHITE = new Color(255, 255, 255).getRGB();
        int BLACK = new Color(0, 0, 0).getRGB();
        int rgb = 0;
        int x1 = width;
        int y1 = height;
        int x2 = 0;
        int y2 = 0;
        int temp1 = 0;
        int temp2 = 0;
        // 方式一：通过getRGB()方式获得像素数组
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                rgb = image.getRGB(i, j);
                if (rgb == -16777216) {
                    temp1 = i;
                    temp2 = j;
                    // 计算最左侧
                    if (x1 >= temp1) {
                        x1 = temp1;
                    }
                    // 计算最右侧
                    if (x2 <= temp1) {
                        x2 = temp1;
                    }
                    // 计算最下方
                    if (y2 <= temp2) {
                        y2 = temp2;
                    }
                    // 计算最上方
                    if (y1 >= temp2) {
                        y1 = temp2;
                    }
                }
            }
        }
        return new int[] {x1, y1, x2 - x1, y2 - y1};
    }

}
